package echo.netty.handler_pipeline;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;

/**
 * @author： zhangnan
 * @date： 2025/5/12 11:01
 * @description： 测试netty的http编解码器
 * @modifiedBy：
 * @version: 1.0
 */
@Slf4j
public class TestHttpServer {

    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup workers = new NioEventLoopGroup(2);
        try {
        // 创建netty 的 server端进行测试
        ChannelFuture channelFuture = new ServerBootstrap()
                .channel(NioServerSocketChannel.class)
                .group(boss, workers)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new HttpServerCodec())
                                // 1. 如果只想处理关心类型，下面这种if else的写法比较啰嗦，可以使用 SimpleChannelInboundHandler
//                                .addLast(new ChannelInboundHandlerAdapter(){
//                                    @Override
//                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                                        log.debug("{}",msg.getClass());
//                                        // 判断类型
//                                        if (msg instanceof HttpRequest) { // 处理请求头
//
//                                        } else if (msg instanceof HttpContent) { // 处理请求体
//
//                                        }
////                                        super.channelRead(ctx, msg);
//                                    }
//                                });
                                // 2. SimpleChannelInboundHandler<你关心的类型>，如示例所示，这里可以只处理 请求头
                                .addLast(new SimpleChannelInboundHandler<HttpRequest>() {
                                    @Override
                                    protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
                                        // 获取请求
                                        log.debug("{}",msg.uri());
                                        // 返回响应，参数1：版本号，参数2：状态码
                                        DefaultFullHttpResponse response = new DefaultFullHttpResponse(msg.protocolVersion(), HttpResponseStatus.OK);

                                        byte[] content = "<h1>Hello, world!</h1>".getBytes();
                                        response.headers().setInt(CONTENT_LENGTH,content.length);
                                        response.content().writeBytes(content);

                                        ctx.writeAndFlush(response);
                                    }
                                });

                    }
                })
                .bind(8080);
            channelFuture.sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            workers.shutdownGracefully();
        }

    }

}
